package com.csj.DesignPattern.factory.config_factory;

import java.io.InputStream;
import java.util.HashMap;
import java.util.Properties;
import java.util.Set;

//咖啡抽象工厂
public class CoffeeFactory {

    private static HashMap<String, Coffee> map = new HashMap<String, Coffee>();

    //静态代码块，在类加载的时候就执行，保证只执行一次
    static {
        //获取到配置文件
        Properties properties = new Properties();
        InputStream resource = CoffeeFactory.class.getClassLoader().getResourceAsStream("bean.yml");
        try {
            //加载配置文件
            properties.load(resource);
            Set<Object> keys = properties.keySet();
            for (Object key : keys) {
                //获取到配置文件中的全类名
                String className = properties.getProperty((String) key);
                //通过全类名反射创建对象
                Class<?> clazz = Class.forName(className);
                Coffee coffee = (Coffee) clazz.newInstance();
                //将创建好的咖啡对象放入map中
                map.put((String) key, coffee);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    public static Coffee createCoffee(String name) {
        //此时map中key为配置文件中的key，value为配置文件中全类名的类的对象
        return map.get(name);
    }
}
